class LinkNode {
    constructor(value,next) {
        this.value = value;
        this.next = next;
    }
}

let link = new LinkNode(1,null);
link.next = new LinkNode(2,null);
link.next.next = new LinkNode(3,null);
link.next.next.next = new LinkNode(4, null);
link.next.next.next.next = new LinkNode(5, null);

// const reverseLink = (link) => {
//     if(link === undefined) return false;
//     let pre = null; let cur = link;
//     while (cur){
//         let next = cur.next;
//         cur.next = pre;
//         pre = cur;
//         cur = next;
//     }
//     return pre;
// }
//
// console.log(reverseLink(link));

// 递归的方式进行反转
const reverse = (head,n) => {
    let pre = head;
    let cur = head;
    let cnt = n;
    // 找出要反转的个数
    while (--n && pre) pre = pre.next;
    if(pre === null) return head;
    pre = null;
    while (cnt--){
        let next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    // 反转后head必须是null了
    head.next = cur;
    return pre;
}

const reverseGroup = (head, k) => {
    // 创建哨兵节点
    let temp = new LinkNode(0, head);
    let p = temp;
    do{
        // 逐段反转
        p.next = reverse(p.next,k);
        // 计算这一段落的偏移量
        for(let i = 0; i < k && p; i++) p = p.next;
        if(p === null) break;
    }while (true)
    return temp.next;
}
console.log(reverseGroup(link,2));









